import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { useSetState } from 'ahooks';

import { Button, Form, Input, message, Select, Spin, Tabs } from 'antd';

import { connect } from 'dva';
import React, { useEffect, useMemo } from 'react';
const FormItem = Form.Item;
const FormList = Form.List;

const dataTypeEnum = [
  {
    label: 'Array',
    value: 'Array',
  },
  {
    label: 'Double',
    value: 'Double',
  },
  {
    label: 'Enumeration',
    value: 'Enumeration',
  },
  {
    label: 'String',
    value: 'String',
  },
  {
    label: 'Integer',
    value: 'Integer',
  },
  {
    label: 'Struct',
    value: 'Struct',
  },
];
interface State {
  loading: boolean;
}
const FormView = props => {
  return <div>{props?.value ?? ''}</div>;
};
const addServer: React.FC = (props: any) => {
  const { dispatch, history, location } = props;
  const [form] = Form.useForm();
  const type = Form.useWatch('type', form);

  const [state, setState] = useSetState<State>({
    loading: false,
  });
  const formItemLayout = {
    // labelCol: {
    //   style: { width: 200 },
    // },
    wrapperCol: {
      span: 12,
    },
  };
  const onFinish = values => {
    const { query } = location;
    const category = Object.assign(
      { array: null, struct: null, enumValue: null, douStrInt: null },
      values.category,
    );
    values.category = category;
    setState({ loading: true });

    dispatch({
      type: 'severDataType/postObjWithRes',
      payload: {
        url: '/api/ms-soa-service/v1/service/library/type/manage',
        id: query.id,
        ...values,
      },
      callback: res => {
        if (res.statusCode === '0') {
          message.success('编辑成功');
          history.push('/soaManage/serviceManage/serviceLibrary?tab=1');
        }
      },
    }).finally(() => {
      setState({ loading: false });
    });
  };
  const getFormDetail = () => {
    const { query } = location;
    if (!query.id) {
      return history.push('/soaManage/serviceManage/serviceLibrary?tab=1');
    }
    setState({ loading: true });
    dispatch({
      type: 'severDataType/getDataWithRes',
      payload: {
        url: '/api/ms-soa-service/v1/service/library/type',
        typeId: query.id,
      },
      callback: res => {
        if (res.statusCode === '0') {
          form.setFieldsValue(res.data ?? {});
        }
      },
    }).finally(() => {
      setState({ loading: false });
    });
  };
  const categoryDetailDom = useMemo(() => {
    const basicDataType = ['Double', 'String', 'Integer'];
    let comDom = <></>;
    if (type === 'Array') {
      comDom = (
        <FormItem {...formItemLayout} label={'数组元素参考数据类型'} name={['category', 'array']}>
          <FormView />
        </FormItem>
      );
    } else if (type === 'Enumeration') {
      comDom = (
        <FormItem {...formItemLayout} label={'枚举值'} name={['category', 'enumValue']}>
          <FormView />
        </FormItem>
      );
    } else if (basicDataType.includes(type)) {
      comDom = (
        <FormItem {...formItemLayout} label={'基础数据类型'} name={['category', 'douStrInt']}>
          <FormView />
        </FormItem>
      );
    } else if (type === 'Struct') {
      comDom = (
        <FormList name={['category', 'struct']}>
          {(fields, { add, remove }) => {
            const items = fields.map((field, index) => ({
              label: index,
              key: field.key + '',
              children: (
                <>
                  <h3 style={{ display: 'flex' }}>
                    <div>结构体信息</div>
                    {/* {fields.length > 1 ? (
                      <Button
                        style={{ marginLeft: 20 }}
                        type="primary"
                        onClick={() => remove(field.name)}
                      >
                        删除结构体成员
                      </Button>
                    ) : null} */}
                  </h3>
                  <FormItem {...formItemLayout} label={'结构体成员名称'} name={[field.name, 'name']}>
                    <FormView />
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label={'结构体参考数据类型'}
                    name={[field.name, 'structReference']}
                  >
                    <FormView />
                  </FormItem>
                </>
              ),
            }));
            return (
              <>
                <h3 style={{ display: 'flex' }}>
                  <div>结构成员位置</div>
                  {/* <Button style={{ marginLeft: 20 }} type="primary" onClick={() => add({})}>
                    添加结构体成员
                  </Button> */}
                </h3>
                <Tabs type="card" items={items} />
              </>
            );
          }}
        </FormList>
      );
    }

    return type ? (
      <>
        <FormItem {...formItemLayout} label={'备注'} name={['remark']}>
          <FormView />
        </FormItem>
        {/* <FormItem noStyle name={'category'}> */}
        {comDom}
        {/* </FormItem> */}
      </>
    ) : null;
  }, [type]);
  useEffect(() => {
    getFormDetail();
  }, []);
  return (
    <Spin spinning={state.loading}>
      <Form
        form={form}
        {...formItemLayout}
        initialValues={{
          category: {},
        }}
        onFinish={onFinish}
      >
        <h3>基本信息</h3>
        <FormItem
          label="数据类型名称"
          name="name"
          rules={[
            {
              whitespace: true,
              message: '请输入数据类型名称',
            },
          ]}
        >
          <FormView />
        </FormItem>
        <FormItem
          label="数据类型描述"
          name="desc"
          rules={[
            {
              required: false,
            },
          ]}
        >
          <FormView />
        </FormItem>
        <FormItem
          label="数据类型命名空间"
          name="nameSpace"
          rules={[
            {
              required: false,
              message: '请输入数据类型命名空间',
            },
          ]}
        >
          <FormView />
        </FormItem>
        <FormItem
          label="数据类型类别"
          name="type"
          rules={[
            {
              whitespace: true,
              message: '请输入数据类型类别',
            },
          ]}
        >
          <FormView />
        </FormItem>
        {categoryDetailDom}
        <FormItem wrapperCol={{ style: { alignItems: 'center', margin: 20 }, span: 24 }}>
          <Button
            type="ghost"
            onClick={() => {
              history.push('/soaManage/serviceManage/serviceLibrary?tab=1');
            }}
          >
            返回
          </Button>
        </FormItem>
      </Form>
    </Spin>
  );
};
export default connect(state => state)(addServer);
